<!DOCTYPE html>
<html>
<head>
<script src="../../resources/js-test.js"></script>
</head>
<body>
<p class="description">
Tests that dispatchEvent raises DISPATCH_REQUEST_ERR if the event
being dispatched is already being dispatched.
</p>
<pre id="console">
</pre>
<script>
if (window.testRunner)
    testRunner.dumpAsText();

jsTestIsAsync = true;

function shouldBeDispatchRequestErr(exception) {
    var ok = Object.getPrototypeOf(exception) == DOMException.prototype && exception.name == 'InvalidStateError';
    (ok ? testPassed : testFailed)("should have got DISPATCH_REQUEST_ERR EventException");
}

// try redispatching an event in the process of being dispatched with
// dispatchEvent

function redispatchCustom(event) {
    try {
        window.dispatchEvent(event);
        testFailed('dispatchEvent of an event being dispatched should throw an exception');
    } catch (ex) {
        shouldBeDispatchRequestErr(ex);
    }

    redispatchCustom.wasInvoked = true;
}

var customEvent = document.createEvent('CustomEvent');
customEvent.initCustomEvent('foo', true, true, null);
var p = document.querySelector('.description');
p.addEventListener('foo', redispatchCustom);
p.dispatchEvent(customEvent);
shouldBeTrue('redispatchCustom.wasInvoked');

// try redispatching an event that has already finished being dispatched

function checkCustom(event) {
    checkCustom.wasInvoked = true;
}

p.removeEventListener('foo', redispatchCustom, true);
p.addEventListener('foo', checkCustom, true);
p.dispatchEvent(customEvent);
shouldBeTrue('checkCustom.wasInvoked');

// try redispatching an event in the process of being dispatched by
// the browser

function redispatchLoad(event) {
    if (redispatchLoad.dispatching) {
        testFailed('dispatchEvent of an event being dispatched should not dispatch the event again');
        return;
    }

    try {
        redispatchLoad.dispatching = true;
        document.dispatchEvent(event);
        testFailed('dispatchEvent of an event being dispatched should throw an exception');
    } catch (ex) {
        shouldBeDispatchRequestErr(ex);
    } finally {
        delete redispatchLoad.dispatching;
    }

    finishJSTest();
}

window.addEventListener('load', redispatchLoad, true);
</script>
</body>
</html>
